import NativeUtils from "./NativeUtils";
import Singleton from "./Singleton";

const { ccclass, property } = cc._decorator;

// import { reportParams, basicConfig } from './config'

import Utils from './common/Util'

declare var wx;


import { AesEncode } from './common/aes'



let systemInfo = {}
// 全局参数
let globalQuery = {}
/**
 * 静态上报所需全局参数 
 */
const reportParams = {
    encryption: 0,
    appName: '花田小农场',
    screenWidth: '',
    screenHeight: '',
    appVersion: '3.0.1',
    sdkVersion: '2.0.0',
    vvid: Utils._newVvid(),
    uuid: Utils._newUuid(),
    // osVersion: osVersion,
    // osType: DeviceInfo.system.indexOf('iOS') !== -1 ? "ios" : "android",
    // model: DeviceInfo.model,
    deviceType: '',
    productId: "6007",
    adPlatform: "weixin",

}
let openId = 'test';
try {
    // 初始化云函数
    wx.cloud.init({
        env: 'huatianxiaonongchang-0b3e5d00ff5', // 你的云开发环境ID
    });
    openId = wx.getStorageSync('openId') || 'test'

    if (!openId || openId == 'test') {
        wx.cloud.callFunction({
            name: 'public',
            data: {
                action: 'getOpenid',
            },
            complete: res => {
                console.log('云函数获取到的openid: ', res)
                if (res.result && res.result.OPENID) {
                    openId = res.result.OPENID
                    wx.setStorageSync('openId', res.result.OPENID)

                }

            }, fail: err => {
                console.log('eeeeee', err)


            }
        })
    }
} catch (error) {

}
@ccclass
export default class HttpHelper extends Singleton<HttpHelper> {
    static baseUrl = 'https://ttsbq.quminglemei.com'

    public newXMLHttpRequest(e: (t: any) => void, t: (error: string) => void): XMLHttpRequest {
        const o = new XMLHttpRequest();
        o.onreadystatechange = () => {
            if (o.readyState === 4) {
                if (o.code === 200) {
                    const n = o.responseText;
                    e && e(n);
                } else if (o.code === 401) {
                    t && t("status : " + o.code);
                } else {
                    t && t("status : " + o.code);
                }
            }
        };
        o.timeout = 10000;
        o.ontimeout = () => {
            t && t("timeout");
        };
        return o;
    }

    public createOneHttpRequest(e: (t: any) => void, t: (error: string) => void = null): XMLHttpRequest {
        return this.newXMLHttpRequest((t) => {
            console.log('xxxxxxxxxx', t)
            let o = {
                code: 0,
                message: "",
                data: {}
            };
            try {
                o = JSON.parse(t);
            } catch (e) {
                console.error("网络发生错误 " + e);
            }
            e && e(o);
        }, t);
    }

    public setHttpHeader(e: XMLHttpRequest): void {

    }
    // static reportPage = (data = {}) => {
    //     let query = { ...globalQuery }

    //     if (data?.MSG) {
    //       query['getAdQuery'] = data.MSG ? data.MSG : ''
    //     }
    //     const ext = encodeURIComponent(AesEncode(JSON.stringify({
    //       ...reportParams,
    //       ...systemInfo,
    //       ...data,


    //       uuRequestId: Utils.createUURequrstId(),
    //       clickId: query['clickid'] ? query['clickid'] : query['click_id'] ? query['click_id'] : "",
    //       imei: query['imei'] ? query['imei'] : "",
    //       oaid: query['oaid'] ? query['oaid'] : "",
    //     })))

    //     wx.request({
    //       url: ReportManager.baseUrl + "/ad/report/adReport",
    //       cachetime: "30",
    //       method: "POST",
    //       data: {
    //         ext

    //       },
    //       success: function (e) { }
    //     })
    //   }
    public wxRequestGet(e: string, t: (t: any) => void, o: (error: string) => void = null): void {
        const requestFn = () => {
            console.log('openIdopenId', openId)
            e += (e.includes("?") ? "&" : "?") + `openId=${openId}&productId=6007&encryption=0`
            wx.request({
                url: HttpHelper.baseUrl + ("/content/" + e).replace(/\/\//g, "/"),
                cachetime: "30",
                method: "Get",
                // data: {
                //   ext

                // },
                success: function (res) {
                    console.log('ressssssssssss', res)
                    if (res.statusCode == "200" && res.data.code == "200") {
                        return t((res.data.data))
                    }
                    return t(res.data)
                },
                fail: (err) => {
                    console.log('err', err)
                    return o(err)
                }
            })
        }
        if (openId == 'test') {
            wx.cloud.callFunction({
                name: 'public',
                data: {
                    action: 'getOpenid',
                },
                complete: res => {
                    console.log('云函数获取到的openid: ', res)
                    if (res.result && res.result.OPENID) {
                        openId = res.result.OPENID
                        wx.setStorageSync('openId', res.result.OPENID)
                        requestFn()
                    }

                }, fail: err => {
                    console.log('eeeeee', err)

                }
            })

        } else {
            requestFn()
        }


    }

    public httpGet(e: string, t: (t: any) => void, o: (error: string) => void = null): void {

        console.error("开始请求0000===> " + e);
        if (!e.includes("http")) {
            e = cc.sys.isNative ? e : HttpHelper.baseUrl + ("/content/" + e).replace(/\/\//g, "/");
        }
        if (cc.sys.isNative) {
            console.error("开始请求===> " + e);

            const regex = /(\?.*)|(\#.*)/gm;
            const urlWithoutParams = e.replace(regex, '');
            NativeUtils.nativePost(urlWithoutParams, getUrlParams(e), t, this, (err) => {
                console.log('eeeeeeee', err)
                if (!o) {
                    console.error(err);
                } else {
                    o(err);
                }
            }, '')
            return;
        }
        e += (e.includes("?") ? "&" : "?") + `openId=${openId}&productId=6007&encryption=0`
        const n = this.createOneHttpRequest(t, o);
        n.withCredentials = false;
        n.open("GET", e, true);
        this.setHttpHeader(n);
        n.send();
        console.error("开始请求===> " + e);

        function getUrlParams(url): { [key: string]: string } {
            const search = url;
            const regex = /[?&]([^=#]+)=([^&#]*)/g;
            const params: { [key: string]: string } = {};
            let match;

            while (match = regex.exec(search)) {
                params[match[1]] = match[2];
            }

            return params;
        }
    }

    httpPost(url, params, cb, errCb = null, timeout = 1e4, n = !1, body = null) {
        try {
            if (!url.includes("http")) {
                url = cc.sys.isNative ? url : HttpHelper.baseUrl + "/content/" + url;
            }
            if (cc.sys.isNative) {
                NativeUtils.nativePost(url, params, cb, this, (err) => {
                    if (!errCb) {
                        console.error(err);
                        // UIManager.show_toast({
                        //     text: "网络异常",
                        //     animation: true
                        // })
                    } else {
                        errCb(err);
                    }
                }, body)
                return;
            }
        } catch (error) {
            console.log('xxxxxxxxxxxxxerrrrrr', error)
        }
    }

    public httpPostByJson(e: string, t: any, o: (t: any) => void, n: (error: string) => void = null): void {
        if (cc.sys.isNative) {
            NativeUtils.httpPost(e, t, o)
            return;
        }
        const r = this.createOneHttpRequest(o, n);
        r.open("POST", e, true);
        r.setRequestHeader("Content-Type", "application/json");
        this.setHttpHeader(r);
        r.send(JSON.stringify(t));
    }

    public httpPostForm(e: string, t: any, o: (t: any) => void, n: (error: string) => void = null): void {
        const r = this.createOneHttpRequest(o, n);
        r.open("POST", e, true);
        r.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        this.setHttpHeader(r);
        r.send(t);
    }
}


